import { createAction } from 'redux-actions'
import { postJson, putJson, body, check, parseJSON, checkStatus, data, getJson } from './util'
import fetch from 'isomorphic-fetch'

export
const fetchUserProfile = createAction('fetch user profile', (userId, cb) =>
	fetch(`/users/${userId}/complete-profile`, getJson)
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
    .then(res => {
      cb && cb();
      return res.data 
    })
)

export
const fetchUserCoreProfile = createAction('fetch user core profile', userId =>
	fetch(`/users/${userId}/core-profile`, getJson)
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
		.then(data)
)

export
const clearUserProfile = createAction('clear user profile')

export
const resetUser = createAction('reset user')

export
const fetchReportLineInfo = createAction('fetch reportLine info', userId =>
	fetch(`/users/profiles/reportline-info/${userId}`, getJson)
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
		.then(data)
)

export
const updateUserProfile = createAction('save user profile', (userId, arg, cb) =>
  fetch(`/users/${userId}/complete-profile/fields`, {
    ...putJson,
    ...body(arg)
  })
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
    .then(res => {
      cb && cb();
      return res.data;
    })
)

export
const updateUserRole = createAction('fetch user role', (roleIds, userId, cb) =>
  fetch('/roles/set-up-roles', {
    ...postJson,
    ...body({
      userId,
      roleIds
    })
  })
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
    .then(cb)
)

export
const updateUserEmployment = createAction('_', (userId, arg, cb) =>
  fetch(`/users/${userId}/user-employment`, {
    ...putJson,
    ...body(arg)
  })
		.then(checkStatus)
		.then(parseJSON)
		.then(check)
    .then(cb)
)

export 
const updateTeamAdmin = createAction('_', (arg, cb) =>
  fetch(`/teams/team-member/set-team-admin`, {
    ...putJson, 
    ...body(arg)
  })
    .then(checkStatus)
    .then(parseJSON)
    .then(check)
    .then(cb)
)

export
const changeUserEmployment = createAction('change user employment');
